package src.provision.subsystem;

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;

import src.constants.ResellerConstants;
import src.reseller.Provision;



public class RMIProvisionerImpl extends UnicastRemoteObject implements Provisioning {
	
	
	private static final String STR_LITE 	= "lite";
	private static final String STR_HISPEED	= "hi-speed";
	private static final String STR_EXTREME	= "extreme";
	
	
	private ArrayList<Customer> aryCustomers;
 

	/**
	 * Constructor
	 * 
	 */
	public RMIProvisionerImpl() throws RemoteException{
		
		
		aryCustomers = new ArrayList();
		// populate a list of known customer infomration which is valid
		aryCustomers.add(new Customer("123", "555-5555"));
		aryCustomers.add(new Customer("456", "555-5556")); 
		aryCustomers.add(new Customer("789", "555-5557"));
		aryCustomers.add(new Customer("101", "555-5558"));
		

    	// register with rmi
    	try {
    		
    		Naming.rebind(ResellerConstants.STR_RMI_PROVISIONING_ADDRESS, this);
			Thread.sleep(1000);
	    	
		} catch (Exception e) {
			System.out.println("[Provisioning] problem binding server");
			e.printStackTrace(); 
		}
		System.out.println("[Provisioning ]Provisioning System is active");

		
	}
	/**
	 * 
	 * @param what the product to provision
	 * @param custNum customer number (from billing system)
	 * @param telNum telephone number to provision the system for
	 * @return a new provision record, <code>null</code> if unable
	 * to provision tohe request
	 * @throws RemoteException if an error occurs
	 */
	public Provision provision(String what, String custNum, String telNum)throws RemoteException {
		// check if it's a valid request
		if(!isValid(what,custNum, telNum)){
			// if not return an invalid provision
			Provision invalidProvision = new RMIProvisionImpl(ResellerConstants.STR_PROVISION_INVALID_ID, -1);
			return invalidProvision;			
		}
		Provision p = new RMIProvisionImpl(ResellerConstants.STR_PROVISION_DUMMY_UNIQUIE_ID, ResellerConstants.LNG_PROVISION_DUMMY_UNIQUIE_TIME);
		return p;
	}

	
	/**
	 * Validate the provision request informatioin
	 * @param inWhat
	 * @param inCustNum
	 * @param inTelNum
	 * @return true if valid; false otherwise.
	 */
	private boolean isValid(String inWhat, String inCustNum, String inTelNum) {
		if(!aryCustomers.contains(new Customer(inCustNum, inTelNum))){
			return false;
		}
		if(inWhat.equals(STR_LITE)
				|| inWhat.equals(STR_HISPEED)
				|| inWhat.equals(STR_EXTREME)){
			return true;
		}

		return false;
	
	}

}
